import json
import re
import os
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from qiniu import Auth, put_data

from apps.user.models import User
from ihome_01 import settings
from utils.views import LoginRequiredJSONMixin

'''
GET /api/v1.0/user
{
    "data": {
        "avatar": "http://oyucyko3w.bkt.clouddn.com/FmWZRObXNX6TdC8D688AjmDAoVrS", 用户头像地址 
        "create_time": "2017-11-07 01:10:21", 用户创建时间 
        "mobile": "18599998888",  mobile
        "name": "哈哈哈哈哈哈",  name
        "user_id": 1 user_id
    },
    "errmsg": "OK",
    "errno": "0"
}
'''


# LoginRequiredJSONMixin
class UserDataView(LoginRequiredJSONMixin, View):
    def get(self, request):
        user = request.user
        # 查询数据
        avatar = str(user.avatar)
        create_time = user.date_joined
        mobile = user.mobile
        name = user.username
        user_id = user.id

        data_dict = {
            "avatar_url": avatar,
            "create_time": create_time,
            "mobile": mobile,
            "name": name,
            "user_id": user_id}
        # 返回响应
        return JsonResponse({
            "data": data_dict,
            "errmsg": "OK",
            "errno": "0"
        })


'''
POST /api/v1.0/user/avatar
avatar
{
    "data": {
        "avatar_url": "http://oyucyko3w.bkt.clouddn.com/FmWZRObXNX6TdC8D688AjmDAoVrS"
    },
    "errno": "0",
    "errmsg": "头像上传成功"
}
'''


class AddAvatarView(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 获取数据
        avatar_file = request.FILES.get('avatar')
        avatar_data = avatar_file.read()
        # 验证数据
        if not avatar_data:
            return JsonResponse({"errno": "400", "errmsg": "上传失败"})
        try:
            q = Auth(access_key=settings.QI_NIU_ACCESS_KEY, secret_key=settings.QI_NIU_SECRET_KEY)
            token = q.upload_token(bucket=settings.BURCKET_NAME)
            ret, res = put_data(token, None, data=avatar_data)
            key = ret.get('key')

        except:
            return JsonResponse({"errno": "400", "errmsg": "上传失败"})
        qn_path = 'http://qihvoz9i7.hn-bkt.clouddn.com/' + key
        user = request.user
        user.avatar = qn_path
        user.save()

        return JsonResponse({"data": {"avatar_url": qn_path},
                             "errno": "0", "errmsg": "头像上传成功"})

        # 返回响应


'''
PUT /api/v1.0/user/name
name 
{
    "errno": "0",
    "errmsg": "修改成功"
}
'''


class UpdateNameView(LoginRequiredJSONMixin, View):
    def put(self, request):
        # 获取参数
        json_dict = json.loads(request.body)
        new_name = json_dict.get('name')
        # 检验参数
        if new_name is None:
            return JsonResponse({'errno': '400', 'errmsg': '缺少参数'})
        user = request.user
        user_id = user.id
        # 查询用户位置 修改信息
        User.objects.filter(id=user_id).update(username=new_name)
        # 返回响应
        return JsonResponse({"errno": "0", "errmsg": "修改成功"})


'''
POST /api/v1.0/user/auth
real_name id_card
{
    "errno": "0",
    "errmsg": "认证信息保存成功"
}
'''


class RealNameView(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 获取参数
        json_dict = json.loads(request.body)
        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')
        # 校验参数
        if not all([real_name, id_card]):
            return JsonResponse({"errno": "400", "errmsg": "信息不全"})
        if not re.match(r'^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                        id_card):
            return JsonResponse({"errno": "400", "errmsg": "身份证错误"})
        # 添加数据
        user = request.user
        user_id = user.id
        User.objects.filter(id=user_id).update(real_name=real_name, id_card=id_card)
        # 　返回响应
        return JsonResponse({"errno": "0", "errmsg": "认证信息保存成功"})

    def get(self, request):
        user = request.user
        real_name = user.real_name
        id_card = user.id_card
        data = {
            'real_name': real_name,
            'id_card': id_card
        }
        response = JsonResponse({'errno': 0, 'data': data})
        return response
